package com.abe.libfitness.main.program;

import android.widget.LinearLayout;
import android.widget.TextView;

import com.abe.libfitness.R;
import com.abe.libfitness.R2;
import com.abe.libfitness.base.BaseComTempActivity;
import com.abe.libfitness.utils.CMDConts;
import com.abe.libfitness.utils.DataCovertUtil;
import com.abe.libfitness.utils.SpFitnessHelper;
import com.abe.libfitness.widget.CircleChartView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public abstract class BaseProgramActivity extends BaseComTempActivity {
    //用户最大力量:牛顿
    protected static int MAX_STRENGTH = 0;
    //用户拉伸距离
    protected static int MAX_DISTANCE = 0;

    @BindView(R2.id.item_title)
    public TextView itemTitle;
    @BindView(R2.id.ll_no1)
    public LinearLayout mNo1Layout;
    @BindView(R2.id.ll_no2)
    public LinearLayout mNo2Layout;
    @BindView(R2.id.ll_no3)
    public LinearLayout mNo3Layout;
    @BindView(R2.id.ll_no4)
    public LinearLayout mNo4Layout;
    @BindView(R2.id.ll_no5)
    public LinearLayout mNo5Layout;
    @BindView(R2.id.finish)
    public TextView finish;
    @BindView(R2.id.report_number2)
    public TextView mTimeTv;
    @BindView(R2.id.report_number)
    public TextView showTargetNumber;
    @BindView(R2.id.report_number3)
    public TextView mCalorieTv;
    @BindView(R2.id.report_number4)
    public TextView mShowWeight;
    @BindView(R2.id.report_number1)
    public TextView mShowRealGroups;
    @BindView(R2.id.myview_circle_chart)
    public CircleChartView mDialChartView;
    @BindView(R2.id.tv_no1)
    public TextView tvNo1;
    @BindView(R2.id.tv_count1)
    public TextView tvCount1;
    @BindView(R2.id.tv_intertime1)
    public TextView tvInterTime1;
    @BindView(R2.id.tv_no2)
    public TextView tvNo2;
    @BindView(R2.id.tv_count2)
    public TextView tvCount2;
    @BindView(R2.id.tv_intertime2)
    public TextView tvInterTime2;
    @BindView(R2.id.tv_no3)
    public TextView tvNo3;
    @BindView(R2.id.tv_count3)
    public TextView tvCount3;
    @BindView(R2.id.tv_intertime3)
    public TextView tvInterTime3;
    @BindView(R2.id.tv_no4)
    public TextView tvNo4;
    @BindView(R2.id.tv_count4)
    public TextView tvCount4;
    @BindView(R2.id.tv_intertime4)
    public TextView tvInterTime4;
    @BindView(R2.id.tv_no5)
    public TextView tvNo5;
    @BindView(R2.id.tv_count5)
    public TextView tvCount5;
    //组数
    protected int mRealGroups = 1;
    //实际重量
    protected int mWeight;
    //计算器
    protected Calendar mCalendar = Calendar.getInstance();
    protected boolean firstTime = true;
    protected boolean isCountDown = true;
    protected Timer mTimer4LogOut = null;
    protected Timer timer;
    protected Timer mChronometer;
    protected Timer weightTime;
    protected int distance = 0;

    protected abstract void initProgram();

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_program_common;
    }

    @Override
    protected void initContent() {
        MAX_STRENGTH = SpFitnessHelper.strength();
        MAX_DISTANCE = SpFitnessHelper.distance();
        if (MAX_STRENGTH == 0 || MAX_DISTANCE == 0) {
            toast("您没有进行力量和距离检测");
            MAX_STRENGTH = 20;
            MAX_DISTANCE = 3500;
        }
        mShowWeight.setText(String.valueOf(mWeight));
        setTextSelectionBg(R.id.ll_no1);
        mShowRealGroups.setText(String.valueOf(mRealGroups));
        mDialChartView.setPercent(0, MAX_DISTANCE * 100 / 3500);
        initProgram();
        // 新建发送任务
        mSendThread = new SendThread(getForceCMD(mWeight), false);
        mSendThread.start();
    }

    @OnClick(R2.id.iv_back)
    public void back() {
        SpFitnessHelper.strength(0);
        SpFitnessHelper.distance(0);
        cancelTimer();
        finish();
    }

    @OnClick(R2.id.zl_zj)
    public void plus() {
        if (mWeight < 100) {
            mWeight++;
            mShowWeight.setText(String.valueOf(mWeight));
        } else {
            toast(R.string.max_weight);
        }
        // 定时开始
        if (weightTime != null) {
            weightTime.cancel();
            weightTime.purge();
            weightTime = null;
        }
        weightTime = new Timer();
        weightTime.schedule(new weightChangeTask(), 2000);
    }

    @OnClick(R2.id.zl_js)
    public void reduce() {
        if (mWeight > 0) {
            mWeight--;
            mShowWeight.setText(String.valueOf(mWeight));
        } else {
            toast(R.string.min_weight);
        }
        // 定时开始
        if (weightTime != null) {
            weightTime.cancel();
            weightTime.purge();
            weightTime = null;
        }
        weightTime = new Timer();
        weightTime.schedule(new weightChangeTask(), 2000);
    }

    /**
     * 获得力量数据
     *
     * @param maxStrength 用户测定最大力量，单位牛顿
     * @return
     */
    protected List<byte[]> getForceCMD(int maxStrength) {
        List<String> forceList = null;
        StringBuilder sDistance_D2 = new StringBuilder(); // 存放写入力量寄存器2命令
        StringBuilder sDistance_D3 = new StringBuilder(); // 存放写入力量寄存器2命令
        StringBuilder sDistance_D4 = new StringBuilder(); // 存放写入力量寄存器2命令
        StringBuilder sDistance_D5 = new StringBuilder(); // 存放写入力量寄存器2命令
        int distance_3 = 0; // 存放距离寄存器3的值
        List<byte[]> cmdList = new ArrayList<>(); // 命令列表
        List<String> forceHeadList = new ArrayList<>(); // 写入力量命令列表
        forceHeadList.add(CMDConts.CMD_WRITE_REIGSTER_F1); // 添加命令头部
        forceHeadList.add(CMDConts.CMD_WRITE_REIGSTER_F2);
        forceHeadList.add(CMDConts.CMD_WRITE_REIGSTER_F3);
        forceHeadList.add(CMDConts.CMD_WRITE_REIGSTER_F4);
        forceHeadList.add(CMDConts.CMD_WRITE_REIGSTER_F5);
        cmdList.add(CMDConts.CMD_WRITE_REIGSTER_F0);

        forceList = getConstantForce(maxStrength);

        if (forceList != null) {
            for (int i = 0; i < forceHeadList.size(); i++) {
                StringBuilder sBuilder = new StringBuilder();
                sBuilder.append(forceHeadList.get(i)); // 添加头部
                sBuilder.append(forceList.get(i)); // 添加力量值
                // 获得并添加CRC校验码
                cmdList.add(DataCovertUtil.getCRC(DataCovertUtil.HexToByteArr(sBuilder.toString())));
            }
        }
        distance_3 = (80 + MAX_DISTANCE) / 2; // 计算距离寄存器D3的值
        sDistance_D2.append(CMDConts.CMD_WRITE_REIGSTER_D2); // 添加头部
        sDistance_D2.append(DataCovertUtil.get4LenString(Integer.toHexString((80 + distance_3) / 2))); // 计算并添加距离值
        sDistance_D3.append(CMDConts.CMD_WRITE_REIGSTER_D3); // 添加头部
        sDistance_D3.append(DataCovertUtil.get4LenString(Integer.toHexString(distance_3))); // 添加距离值
        sDistance_D4.append(CMDConts.CMD_WRITE_REIGSTER_D4); // 添加头部
        sDistance_D4.append(DataCovertUtil.get4LenString(Integer.toHexString((distance_3 + MAX_DISTANCE) / 2)));// 添加距离值
        sDistance_D5.append(CMDConts.CMD_WRITE_REIGSTER_D5); // 添加头部
        sDistance_D5.append(DataCovertUtil.get4LenString(Integer.toHexString(MAX_DISTANCE))); // 添加距离值
        cmdList.add(CMDConts.CMD_WRITE_REIGSTER_D0); // 添加距离寄存器D0的命令
        cmdList.add(CMDConts.CMD_WRITE_REIGSTER_D1); // 添加距离寄存器D1的命令
        cmdList.add(DataCovertUtil.getCRC(DataCovertUtil.HexToByteArr(sDistance_D2.toString()))); // 计算并添加距离寄存器D2命令的CRC校验码
        cmdList.add(DataCovertUtil.getCRC(DataCovertUtil.HexToByteArr(sDistance_D3.toString()))); // 计算并添加距离寄存器D3命令的CRC校验码
        cmdList.add(DataCovertUtil.getCRC(DataCovertUtil.HexToByteArr(sDistance_D4.toString()))); // 计算并添加距离寄存器D4命令的CRC校验码
        cmdList.add(DataCovertUtil.getCRC(DataCovertUtil.HexToByteArr(sDistance_D5.toString()))); // 计算并添加距离寄存器D5命令的CRC校验码
        cmdList.add(CMDConts.CMD_READ_REGISTER_3_4); // 添加读取寄存器3、4命令
        return cmdList;
    }

    /**
     * 获得恒力力量
     */
    protected List<String> getConstantForce(int maxStrength) {
        List<String> list = new ArrayList<String>();
        String force = DataCovertUtil.get4LenString(Integer.toHexString((int) (33.33 * maxStrength))); // 获得四位字符串型力量的值
        list.add(force);
        list.add(force);
        list.add(force);
        list.add(force);
        list.add(force);
        return list;
    }

    /**
     * 根据命令设置背景颜色
     *
     * @param resId resId
     */
    public void setTextSelectionBg(int resId) {
        if (resId == R.id.ll_no1) {
            mNo1Layout.setBackgroundResource(R.mipmap.ic_textview_bg);
            mNo2Layout.setBackground(null);
            mNo3Layout.setBackground(null);
            mNo4Layout.setBackground(null);
            mNo5Layout.setBackground(null);
        } else if (resId == R.id.ll_no2) {
            mNo2Layout.setBackgroundResource(R.mipmap.ic_textview_bg);
            mNo1Layout.setBackground(null);
            mNo3Layout.setBackground(null);
            mNo4Layout.setBackground(null);
            mNo5Layout.setBackground(null);
        } else if (resId == R.id.ll_no3) {
            mNo3Layout.setBackgroundResource(R.mipmap.ic_textview_bg);
            mNo2Layout.setBackground(null);
            mNo1Layout.setBackground(null);
            mNo4Layout.setBackground(null);
            mNo5Layout.setBackground(null);
        } else if (resId == R.id.ll_no4) {
            mNo4Layout.setBackgroundResource(R.mipmap.ic_textview_bg);
            mNo2Layout.setBackground(null);
            mNo3Layout.setBackground(null);
            mNo1Layout.setBackground(null);
            mNo5Layout.setBackground(null);
        } else if (resId == R.id.ll_no5) {
            mNo5Layout.setBackgroundResource(R.mipmap.ic_textview_bg);
            mNo2Layout.setBackground(null);
            mNo3Layout.setBackground(null);
            mNo4Layout.setBackground(null);
            mNo1Layout.setBackground(null);
        }
    }


    protected void resetCalendar() {
        mCalendar.set(Calendar.HOUR_OF_DAY, 0);
        mCalendar.set(Calendar.MINUTE, 0);
        mCalendar.set(Calendar.SECOND, 0);
    }

    protected void cancelTimer() {
        if (timer != null) {
            timer.cancel();
        }
        if (mChronometer != null) {
            mChronometer.cancel();
        }
        if (mTimer4LogOut != null) {
            mTimer4LogOut.cancel();
        }
        if (weightTime != null) {
            weightTime.cancel();
        }
    }

    protected void resetTimer4LogOut() {
        if (mTimer4LogOut != null) {
            mTimer4LogOut.cancel();
            mTimer4LogOut.purge();
            mTimer4LogOut = null;
        }
        mTimer4LogOut = new Timer();
        // 1分钟不操作自动上传数据
        mTimer4LogOut.schedule(new Task4Logout(), 60 * 1000);
    }

    protected void showClock(TextView tv) {
        timer = new Timer();
        timer.schedule(new TrainTask(tv), 1000, 1000);
    }

    class Task4Logout extends TimerTask {
        @Override
        public void run() {
            runOnUiThread(BaseProgramActivity.this::finish);
        }
    }

    class weightChangeTask extends TimerTask {
        @Override
        public void run() {
            closeSendThread();
            mSendThread = new SendThread(getForceCMD(mWeight), false);
            mSendThread.start();
        }
    }

    class TrainTask extends TimerTask {
        TrainTask(TextView tv) {
            mTimeTv = tv;
        }

        @Override
        public void run() {
            runOnUiThread(() -> {
                // 每次秒数+1
                mCalendar.add(Calendar.SECOND, 1);
                mTimeTv.setText(String.format("%s:%s", DataCovertUtil.get2LenString(mCalendar.get(Calendar.MINUTE)), DataCovertUtil.get2LenString(mCalendar.get(Calendar.SECOND))));
            });
        }
    }
}